package com.huiyujinrong.qiangdanbao.activity.my;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.huiyujinrong.qiangdanbao.R;
import com.huiyujinrong.qiangdanbao.bean.FirstTradeRecord;
import com.huiyujinrong.qiangdanbao.bean.UserStatusBean;
import com.huiyujinrong.qiangdanbao.network.Api;
import com.huiyujinrong.qiangdanbao.utils.AliPayOderInfo;
import com.huiyujinrong.qiangdanbao.utils.AuthResult;
import com.huiyujinrong.qiangdanbao.utils.PayResult;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;
import com.umeng.analytics.MobclickAgent;

import java.util.Map;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class UserRechargeActivity extends AppCompatActivity implements UserRechargeContract.View {



    @BindView(R.id.toolbar_Title)
    TextView title;

    @BindView(R.id.toolbar_Back)
    RelativeLayout back;

    @BindView(R.id.toolbar_Save)
    TextView toolbar_Save;

    @BindView(R.id.m_money)
    TextView m_money;

    @BindView(R.id.tvTips)
    TextView tvTips;
    @BindView(R.id.tvTips2)
    TextView tvTips2;
    @BindViews({R.id.money_yibai, R.id.money_wubai, R.id.money_yiqian})
    RadioButton[] radioButtons;
    private ProgressDialog loadingDialog;
    private AlertDialog alipayDialog;
    private String APPID;
    private String RSA2_PRIVATE;
    private String RSA_PRIVATE;

    private Toast t;

    private static final int SDK_PAY_FLAG = 0xFF;
    private static final int SDK_AUTH_FLAG = 2;

    private static float choiceMoney = 0f;

    private UserRechargePresenter presenter;

    private boolean isFirst = false;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功");
                        MobclickAgent.onEvent(UserRechargeActivity.this, "zhi_fu");   //UM支付
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(UserRechargeActivity.this, "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
                        showToast("授权成功");
                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(UserRechargeActivity.this, "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        showToast("授权失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    private class MPayTask implements Runnable {
        private Activity activity;
        private String orderInfo;

        public MPayTask(Activity activity, String orderInfo) {
            this.orderInfo = orderInfo;
            this.activity = activity;
        }

        @Override
        public void run() {
            PayTask alipay = new PayTask(activity);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.money);
        ButterKnife.bind(this);
        presenter = new UserRechargePresenter(this);
        presenter.start();

        createAlipayDialog();
        loadingDialog = createProgressDialog();
        inSetToolBar();
        radioButtons[1].setChecked(true);
        APPID = getResources().getString(R.string.ALIPAY_ID);
        RSA2_PRIVATE = getResources().getString(R.string.RSA2_PRIVATE);
        RSA_PRIVATE = getResources().getString(R.string.RSA_PRIVATE);
    }

    private ProgressDialog createProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载中");
        return progressDialog;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        presenter.selectUserStatus(String.valueOf(SharedHelper.get(this, Api.USER_ID, Api.nul)));

        presenter.findUserFirstTradeRecord(String.valueOf(SharedHelper.get(this, "user_id", "")));
    }

    //充值
    @OnClick(R.id.rc_alipay)
    void AliPay() {

        if (radioButtons[0].isChecked()) {
            choiceMoney = 100f;
        } else if (radioButtons[1].isChecked()) {
            choiceMoney = 500f;
        } else if (radioButtons[2].isChecked()) {
            choiceMoney = 1000f;
        }
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            alipayDialog.show();
        } else {

            //调用支付宝
            String orderInfo = createOderInfo(choiceMoney);
            MPayTask mPayTask = new MPayTask(this, orderInfo);
            Thread thread = new Thread(mPayTask);
            thread.start();
        }
    }

    //设置title
    private void inSetToolBar() {
        back.setVisibility(View.VISIBLE);
        toolbar_Save.setVisibility(View.VISIBLE);
        title.setText("充值");
    }

    //关闭当前
    @OnClick(R.id.toolbar_Back)
    void onBack() {
        finish();
    }

    //交易记录
    @OnClick(R.id.toolbar_Save)
    void onRecord() {
        startActivity(new Intent(this, RecordActivity.class));
    }

    private String createOderInfo(float money) {

        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        String uid = (String) SharedHelper.get(this, "user_id", "");
        return AliPayOderInfo.build().setAppId(APPID)//支付宝APPID
                .setRsa2(rsa2)//是否为rsa加密
                .setMoney(money)//支付金额
                .setPassback(uid + "-C-")//用户参数
                .setNotifyUrl(Api.NOTITY_URL)//服务端请求地址
                .setPrivateKey(RSA_PRIVATE)//签名
                .setSubject("用户" + Api.tel + "充值")   //充值信息
                .setBody(getString(R.string.qiangdanbao))  //商品描述
                .builder().getOrderInfo();
    }

    private void createAlipayDialog() {
        alipayDialog = new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        //
                        finish();
                    }
                }).create();
    }

    @Override
    public void showLoadingDialog() {
        loadingDialog.show();
    }

    @Override
    public void finishLoadingDialog() {
        loadingDialog.dismiss();
    }

    @Override
    public void getData(UserStatusBean bean) {
        m_money.setText(bean.getBalance() + "");
    }

    @Override
    public void showToast(String str) {
        if (t == null) {
            t = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        } else {
            t.setText(str);
            t.setDuration(Toast.LENGTH_SHORT);
        }
        t.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.end();
    }

    @Override
    public void findFirstTrade(FirstTradeRecord firstTradeRecord) {
        if (firstTradeRecord != null) {
            if (firstTradeRecord.isFirst()) {
                tvTips.setVisibility(View.GONE);
                tvTips2.setVisibility(View.GONE);
            } else {
                tvTips.setVisibility(View.VISIBLE);
                tvTips2.setVisibility(View.VISIBLE);
            }
        }
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
